package com.zg.common.lock.service.impl;

import com.zg.common.lock.service.LockService;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/5/20 19:20
 */

import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 分布式锁服务实现
 */
@Service
@RequiredArgsConstructor
@Primary
public class RedissonServiceImpl implements LockService {

    private final RedissonClient redissonClient;

    @Override
    public void lock(String lockKey) {
        if (lockKey == null) {
            throw new IllegalArgumentException("lockKey不能为空");
        }
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
    }

    @Override
    public void unlock(String lockKey) {
        if (lockKey == null) {
            throw new IllegalArgumentException("lockKey不能为空");
        }
        RLock lock = redissonClient.getLock(lockKey);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

    @Override
    public boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit) {
        if (lockKey == null) {
            throw new IllegalArgumentException("lockKey不能为空");
        }
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }
}